﻿using System;
using System.Composition;
using System.Threading.Tasks;
using Unread.Business.Data.Syndication;
using Unread.Business.Models;
using Unread.Business.Repositories.Interfaces;
using Unread.Business.Services.Interfaces;
using Windows.Web.Syndication;

namespace Unread.Business.Services
{
    [Export(typeof(IFeedAdder))]
    internal class FeedAdder : IFeedAdder
    {
        private readonly ISyndicationClient _syndicationClient;
        private readonly IFeedRepository _feedRepository;

        [ImportingConstructor]
        public FeedAdder(ISyndicationClient syndicationClient, IFeedRepository feedRepository)
        {
            if (syndicationClient == null) throw new ArgumentNullException("syndicationClient");
            if (feedRepository == null) throw new ArgumentNullException("feedRepository");

            _syndicationClient = syndicationClient;
            _feedRepository = feedRepository;
        }

        public async Task Add(Uri syndicationUri)
        {
            if (syndicationUri == null) throw new ArgumentNullException("syndicationUri");

            var feed = await DownloadFeed(syndicationUri);

            await _feedRepository.Create(feed);
        }

        private async Task<Feed> DownloadFeed(Uri syndicationUri)
        {
            var syndicationFeed = await _syndicationClient.RetrieveFeedAsync(syndicationUri);

            var feed = new Feed
            {
                SyndicationUri = syndicationUri,
                Website = syndicationFeed.FirstUri,
                Title = syndicationFeed.Title.GetText(syndicationUri.Host),
                Subtitle = syndicationFeed.Subtitle.GetText(),
                Image = syndicationFeed.ImageUri,
                LastRead = DateTime.Now.AddDays(-7)
            };

            return feed;
        }
    }
}
